package com.qqt.csr.web.controller;

import com.qqt.csr.common.acl.aics.AICustomerServiceClient;
import com.qqt.csr.common.enums.AuthorizeSourceEnum;
import com.qqt.csr.common.exception.StatusCode;
import com.qqt.csr.common.idempotent.Idempotent;
import com.qqt.csr.common.interceptor.auth.Authorize;
import com.qqt.csr.common.log.Log;
import com.qqt.csr.common.operalog.BusinessType;
import com.qqt.csr.common.operalog.LogLevel;
import com.qqt.csr.common.operalog.OperationLog;
import com.qqt.csr.common.session.SessionContextHolder;
import com.qqt.csr.common.utils.ServiceAssert;
import com.qqt.csr.common.vo.resp.ObjectResponse;
import com.qqt.csr.im.entity.Account;
import com.qqt.csr.im.service.AccountService;
import com.qqt.csr.web.service.AcceptingConversationService;
import com.qqt.csr.web.service.ClosingConversationService;
import com.qqt.csr.web.service.ImAccountService;
import com.qqt.csr.web.service.SwitchingCsStatusService;
import com.qqt.csr.web.vo.req.*;
import com.qqt.csr.web.vo.resp.CsStatusRespVO;
import com.qqt.csr.web.vo.resp.VisitorConversationInfoRespVO;
import com.qqt.csr.web.vo.resp.VisitorImAccountInfoRespVO;
import com.qqt.csr.workbench.service.SkillSetConfigService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("workbench")
@Tag(name = "客服工作台", description = "客服工作台")
public class WorkbenchController {
    @Autowired
    private ClosingConversationService closingConversationService;
    @Autowired
    private AcceptingConversationService acceptingConversationService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private SwitchingCsStatusService switchingCsStatusService;
    @Autowired
    private ImAccountService imAccountService;
    @Autowired
    private AICustomerServiceClient aiCustomerServiceClient;
    @Autowired
    private SkillSetConfigService skillSetConfigService;

    @Authorize(source = AuthorizeSourceEnum.H5)
    @PostMapping("/member/transfer")
    @Operation(summary = "访客转人工客服专线")
    @Log(desc = "访客转人工客服专线")
    @Idempotent(model = "transfer:")
    public ObjectResponse<VisitorConversationInfoRespVO> transfer(@Validated @RequestBody AcceptingConversationReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        req.setTenantId(tenantId);
        VisitorConversationInfoRespVO result = acceptingConversationService.accept(req);
        return ObjectResponse.success(result);
    }

    @Authorize(source = AuthorizeSourceEnum.H5)
    @PostMapping("/member/getImAccount")
    @Log(desc = "访客获取IM账户信息")
    @Operation(summary = "访客获取IM账户信息")
    public ObjectResponse<VisitorImAccountInfoRespVO> getImAccount(@Validated @RequestBody CreatingChannelUserImAccountReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        Account account = imAccountService.createOrUpdateVisitorImAccount(req);
        String websocketAddress = imAccountService.getWebsocketAddress(tenantId, account, req.getDeviceFlag(), req.getDeviceType());
        return ObjectResponse.success(VisitorImAccountInfoRespVO.builder().imAccountId(account.getId()).webSocketUrl(websocketAddress).build());
    }

    @Authorize(source = AuthorizeSourceEnum.H5)
    @PostMapping("/member/getUnClosedConversation")
    @Log(desc = "访客获取已存在未结束的会话")
    @Operation(summary = "访客获取已存在未结束的会话")
    public ObjectResponse<VisitorConversationInfoRespVO> getUnClosedConversation(@Validated @RequestBody AcceptingConversationReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        req.setTenantId(tenantId);
        VisitorConversationInfoRespVO result = acceptingConversationService.getUnClosedConversation(req);
        return ObjectResponse.success(result);
    }

    @Authorize
    @PostMapping("/conversation/close")
    @Operation(summary = "人工客服结束会话")
    @Log(desc = "人工客服结束会话")
    @Idempotent(model = "cs-close:")
    @OperationLog(level = LogLevel.MIDDLE, operationMenu = "客服工作台", buttonName = "结束会话", businessType = BusinessType.UPDATE)
    public ObjectResponse<String> closeConversation(@Validated @RequestBody ClosingConversationReqVO req) {
        closingConversationService.closeConversation(req.getConversationId(), SessionContextHolder.getHeaderInfo().getUserId());
        return ObjectResponse.success();
    }

    @Authorize
    @PostMapping("/cs/status/switch")
    @Operation(summary = "切换客服状态")
    @Log(desc = "切换客服状态")
    @OperationLog(level = LogLevel.MIDDLE, operationMenu = "客服工作台", buttonName = "切换就绪状态", businessType = BusinessType.UPDATE)
    public ObjectResponse<CsStatusRespVO> switchCsStatus(@Validated @RequestBody UpdatingCsStatusReqVO req) {
        ServiceAssert.notNull(req, StatusCode.Common.NULL_ERROR.getCode(), "请求参数不能为空");
        Long csId = SessionContextHolder.getHeaderInfo().getUserId();
        CsStatusRespVO csStatusRespVO = switchingCsStatusService.switchStatus(csId, req.getReadyStatus(), req.getWorkStatus());
        return ObjectResponse.success(csStatusRespVO);
    }

    @Authorize
    @GetMapping("/cs/status/query")
    @Operation(summary = "获取客服状态")
    public ObjectResponse<CsStatusRespVO> queryCsStatus() {
        String tenantId = SessionContextHolder.getHeaderInfo().getTenantId();
        Long csId = SessionContextHolder.getHeaderInfo().getUserId();
        String csName = SessionContextHolder.getHeaderInfo().getNickName();
        String csHeadImg = SessionContextHolder.getHeaderInfo().getHeadImgUrl();
        CsStatusRespVO csStatusRespVO = switchingCsStatusService.queryStatus(tenantId, csId, csName, csHeadImg);
        return ObjectResponse.success(csStatusRespVO);
    }

    @Authorize
    @PostMapping("/cs/visitorAccessCount/query")
    @Operation(summary = "今日访客转人工次数")
    public ObjectResponse<Long> queryVisitorAccessCount(@Validated @RequestBody QueryingVisitorAccessCountReqVO req) {
        long accessCsCount = acceptingConversationService.getVisitorAccessCsCount(req.getVisitorImAccountId());
        return ObjectResponse.success(accessCsCount);
    }

    @Authorize
    @GetMapping("/cs/csAccessVisitorCount/query")
    @Operation(summary = "后台首页客服今日接待访客数量")
    public ObjectResponse<Long> getCsAccessVisitorCount() {
        Long csId = SessionContextHolder.getHeaderInfo().getUserId();
        Long accessCount = acceptingConversationService.getCsAccessVisitorCount(csId);
        return ObjectResponse.success(accessCount);
    }
}
